package Datos;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.StreamCorruptedException;
import java.math.BigInteger;
import java.security.MessageDigest;

//import sun.security.provider.MD5;


public class Disco {
	private static Disco instancia;
	protected Disco(){}
	
	public static Disco getInstance(){
		if(instancia == null){
			instancia = new Disco();
		}
		return instancia;
	}
	
	private String transformarPath(String path){
		String osname = System.getProperty("os.name");
		if(osname.startsWith("Windows")){
			path = path.replace("/", "\\");
		}
		return path;
	}
	
	public void writeObject(Object ob, String filename) throws SecurityException, FileNotFoundException, IOException {
		filename = transformarPath(filename);
		ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(filename));
		out.writeObject(ob);
		out.close();
		
	}
	
	public void writeFile (String text, String filename) throws IOException{
		filename = transformarPath(filename);
		FileWriter out = new FileWriter(filename);
		out.write(text);
		out.close();
	}
	
	public Object getObject(String filename) throws StreamCorruptedException, FileNotFoundException, IOException, ClassNotFoundException{
		filename = transformarPath(filename);
		ObjectInputStream in = new ObjectInputStream(new FileInputStream(filename));
		Object obj = in.readObject();
		in.close();
		return obj;
	}
	
	public String getFile(String filename) throws IOException{
		filename = transformarPath(filename);
		StringBuffer text = new StringBuffer(1000);
		BufferedReader in = new BufferedReader(new FileReader(filename));
		char buf[] = new char[1024];
		int read = 0;
		while((read=in.read(buf)) != -1){
			text.append(buf,0,read);
		}
		in.close();
		return text.toString();
	}
	
	public File getAFile(String filename){
		File file = new File(filename);
		return file;
	}
	
	public String copyToPool(String filename) throws Exception{
		File src = new File(filename);
		MessageDigest md = MessageDigest.getInstance("MD5");
		String text = getFile(filename);
		md.update(text.getBytes());
		BigInteger bi = new BigInteger(1,md.digest());
		String outFilename = bi.toString(16);
		File dst = new File("pool"+File.separator+outFilename);
		BufferedWriter out = new BufferedWriter(new FileWriter(dst));
		out.write(text);
		out.close();
		return outFilename;
	}
}
